<template>
  <div class="study-notes-container">
    <home-header />
    <div class="study-notes-content tags-layout">
      <!-- 左侧标签栏：新增/编辑时隐藏，并加过渡动画 -->
      <transition name="fade-tagbar">
        <div v-if="!isEditing" class="tags-sidebar">
          <div class="add-tag-row">
            <el-button size="mini" icon="el-icon-plus" type="primary" @click="addTagDialogVisible = true">添加标签</el-button>
          </div>
          <el-dialog
            title="新建标签"
            :visible.sync="addTagDialogVisible"
            width="320px"
            @opened="$nextTick(() => $refs.addTagInput && $refs.addTagInput.focus())"
          >
            <el-input
              v-model="newTagInput"
              ref="addTagInput"
              placeholder="请输入新标签"
              @keyup.enter="handleAddTag"
              maxlength="10"
              show-word-limit
            />
            <span slot="footer" class="dialog-footer">
              <el-button @click="addTagDialogVisible = false">取消</el-button>
              <el-button type="primary" @click="handleAddTag">确定</el-button>
            </span>
          </el-dialog>
          <div
            v-for="tag in ['全部', ...allTags]"
            :key="tag"
            :class="['tag-item', {active: selectedTag === tag}]"
            @click="selectedTag = tag"
          >
            {{ tag }}
            <template v-if="tag !== '全部'">
              <el-button
                type="text"
                icon="el-icon-close"
                size="mini"
                class="tag-delete-btn"
                @click.stop="deleteTag(tag)"
              />
            </template>
          </div>
        </div>
      </transition>
      <!-- 右侧内容区：只切换列表/编辑器 -->
      <div class="notes-card">
        <h2 class="notes-title">学习笔记</h2>
        <div v-if="!isEditing">
          <!-- 笔记列表 -->
          <div class="notes-list">
            <div class="notes-header-pro right-align-btn">
              <el-button type="primary" icon="el-icon-plus" @click="createNewNote">新建笔记</el-button>
            </div>
            <div v-if="filteredNotes.length === 0" class="notes-empty-pro">
              <svg class="notes-empty-svg" width="120" height="120" viewBox="0 0 120 120" fill="none"><circle cx="60" cy="60" r="56" fill="#f3f6fa"/><rect x="30" y="40" width="60" height="40" rx="8" fill="#e0e7ef"/><rect x="38" y="48" width="44" height="8" rx="4" fill="#c9d6e6"/><rect x="38" y="62" width="28" height="8" rx="4" fill="#c9d6e6"/></svg>
              <div class="notes-empty-text-pro">还没有任何学习笔记，点击右上角"新建笔记"开始记录你的成长吧！</div>
            </div>
            <transition-group name="fade-card" tag="div" class="notes-grid-pro" v-else>
              <div v-for="note in filteredNotes" :key="note.id" class="note-card-pro" @click="editNote(note)">
                <div class="note-card-header">
                  <h3 class="note-title-pro">{{ note.title }}</h3>
                  <span class="note-date-pro">{{ formatDate(note.date) }}</span>
                </div>
                <div class="note-tags">
                  <el-tag v-for="tag in note.tags" :key="tag" size="mini">{{ tag }}</el-tag>
                </div>
                <div class="note-preview-pro" v-html="note.content"></div>
                <div class="note-card-actions">
                  <el-button type="text" icon="el-icon-edit" @click.stop="editNote(note)">编辑</el-button>
                  <el-button type="text" icon="el-icon-delete" @click.stop="deleteNote(note.id)">删除</el-button>
                </div>
              </div>
            </transition-group>
          </div>
        </div>
        <div v-else>
          <!-- 编辑器区 -->
          <div class="notes-editor-pro">
            <div class="editor-header-pro">
              <el-button icon="el-icon-arrow-left" @click="cancelEdit" class="back-btn-pro">返回</el-button>
              <el-input
                v-model="currentNote.title"
                placeholder="请输入标题"
                class="title-input-pro"
              ></el-input>
              <div class="editor-actions-pro">
                <el-button type="primary" @click="previewNote">预览</el-button>
                <el-button type="success" @click="saveNote">保存</el-button>
              </div>
            </div>
            <el-select
              v-model="currentNote.tags"
              multiple
              filterable
              allow-create
              default-first-option
              placeholder="请选择标签"
              style="width: 100%; margin-bottom: 16px;"
            >
              <el-option
                v-for="tag in allTags"
                :key="tag"
                :label="tag"
                :value="tag"
              />
            </el-select>
            <div class="editor-content-pro">
              <quill-editor
                v-model="currentNote.content"
                ref="quillEditor"
                :options="editorOption"
                @change="onEditorChange"
              ></quill-editor>
            </div>
            <div class="auto-save-tip">内容会自动保存在本地，不用担心丢失哦~</div>
          </div>
          <!-- 预览对话框 -->
          <el-dialog
            title="笔记预览"
            :visible.sync="previewVisible"
            width="800px"
            class="preview-dialog"
          >
            <div class="preview-content">
              <h1>{{ currentNote.title }}</h1>
              <div v-html="currentNote.content"></div>
            </div>
          </el-dialog>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import HomeHeader from '@/components/HomeHeader.vue'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import { quillEditor } from 'vue-quill-editor'

export default {
  name: 'StudyNotesView',
  components: {
    HomeHeader,
    quillEditor
  },
  data() {
    return {
      isEditing: false,
      previewVisible: false,
      notes: [],
      allTags: ['学习', '工作', '生活'],
      selectedTag: '全部',
      currentNote: {
        id: null,
        title: '',
        content: '',
        tags: [],
        date: new Date()
      },
      editorOption: {
        placeholder: '请输入笔记内容...',
        modules: {
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'],
            ['blockquote', 'code-block'],
            [{ 'header': 1 }, { 'header': 2 }],
            [{ 'list': 'ordered' }, { 'list': 'bullet' }],
            [{ 'script': 'sub' }, { 'script': 'super' }],
            [{ 'indent': '-1' }, { 'indent': '+1' }],
            [{ 'direction': 'rtl' }],
            [{ 'size': ['small', false, 'large', 'huge'] }],
            [{ 'header': [1, 2, 3, 4, 5, 6, false] }],
            [{ 'color': [] }, { 'background': [] }],
            [{ 'font': [] }],
            [{ 'align': [] }],
            ['clean'],
            ['link', 'image']
          ]
        }
      },
      newTagInput: '',
      addTagDialogVisible: false
    }
  },
  computed: {
    sortedNotes() {
      return this.notes.slice().sort((a, b) => new Date(b.date) - new Date(a.date));
    },
    filteredNotes() {
      if (this.selectedTag === '全部') return this.sortedNotes;
      return this.sortedNotes.filter(note => note.tags && note.tags.includes(this.selectedTag));
    }
  },
  created() {
    this.loadTags()
    this.loadNotes()
  },
  methods: {
    loadTags() {
      const savedTags = localStorage.getItem('allTags')
      if (savedTags) {
        this.allTags = JSON.parse(savedTags)
      }
    },
    loadNotes() {
      const savedNotes = localStorage.getItem('studyNotes')
      if (savedNotes) {
        this.notes = JSON.parse(savedNotes)
        // 合并所有标签到allTags
        const tagSet = new Set(this.allTags)
        this.notes.forEach(note => {
          if (note.tags) note.tags.forEach(tag => tagSet.add(tag))
        })
        this.allTags = Array.from(tagSet)
        this.saveTags();
      }
    },
    saveTags() {
      localStorage.setItem('allTags', JSON.stringify(this.allTags))
    },
    saveNotes() {
      localStorage.setItem('studyNotes', JSON.stringify(this.notes))
    },
    createNewNote() {
      this.currentNote = {
        id: Date.now(),
        title: '',
        content: '',
        tags: [],
        date: new Date()
      }
      this.isEditing = true
    },
    editNote(note) {
      this.currentNote = { ...note }
      this.isEditing = true
    },
    deleteNote(id) {
      this.$confirm('确定要删除这篇笔记吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.notes = this.notes.filter(note => note.id !== id)
        this.saveNotes()
        this.$message.success('删除成功')
      }).catch(() => {})
    },
    cancelEdit() {
      this.isEditing = false
      this.currentNote = {
        id: null,
        title: '',
        content: '',
        tags: [],
        date: new Date()
      }
    },
    previewNote() {
      this.previewVisible = true
    },
    saveNote() {
      if (!this.currentNote.title.trim()) {
        this.$message.error('标题不能为空');
        return;
      }
      if (!this.currentNote.content || this.currentNote.content.replace(/<(.|\n)*?>/g, '').trim() === '') {
        this.$message.error('内容不能为空');
        return;
      }
      if (!this.currentNote.tags || this.currentNote.tags.length === 0) {
        this.$message.error('请至少选择一个标签');
        return;
      }
      // 合并新标签到allTags
      let hasNewTag = false;
      this.currentNote.tags.forEach(tag => {
        if (!this.allTags.includes(tag)) {
          this.allTags.push(tag)
          hasNewTag = true;
        }
      })
      if (hasNewTag) this.saveTags();
      // 每次保存都更新时间
      this.currentNote.date = new Date()
      const index = this.notes.findIndex(note => note.id === this.currentNote.id)
      if (index > -1) {
        this.$set(this.notes, index, { ...this.currentNote })
      } else {
        this.notes.unshift({ ...this.currentNote })
      }
      this.saveNotes()
      this.isEditing = false
      this.$message.success('保存成功')
    },
    onEditorChange({ html }) {
      this.currentNote.content = html
    },
    formatDate(date) {
      const d = new Date(date);
      const pad = n => n.toString().padStart(2, '0');
      return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
    },
    handleAddTag() {
      const tag = this.newTagInput.trim();
      if (!tag) return;
      if (this.allTags.includes(tag)) {
        this.$message.warning('标签已存在');
        return;
      }
      this.allTags.push(tag);
      this.saveTags();
      this.newTagInput = '';
      this.addTagDialogVisible = false;
      this.$message.success('标签添加成功');
    },
    deleteTag(tag) {
      this.$confirm(`确定要删除标签"${tag}"吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.allTags = this.allTags.filter(t => t !== tag);
        this.saveTags();
        // 所有笔记移除该标签
        this.notes.forEach(note => {
          if (note.tags) note.tags = note.tags.filter(t => t !== tag);
        });
        this.saveNotes();
        if (this.selectedTag === tag) this.selectedTag = '全部';
        this.$message.success('标签已删除');
      });
    }
  }
}
</script>

<style scoped>
.study-notes-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #f7f8fa 0%, #eef2f7 100%);
}

.study-notes-content {
  display: flex;
  justify-content: center;
  align-items: flex-start;
  padding-top: 110px;
  min-height: 80vh;
}

.notes-card {
  background: #fff;
  border-radius: 16px;
  box-shadow: 0 4px 24px rgba(0,0,0,0.08);
  padding: 40px 36px 32px 36px;
  width: 1000px;
  max-width: 100vw;
}

.notes-title {
  font-size: 1.5rem;
  font-weight: 700;
  color: #222;
  margin-bottom: 28px;
  letter-spacing: 1px;
}

.notes-header-pro {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding-bottom: 18px;
  border-bottom: 1.5px solid #f0f2f5;
  margin-bottom: 24px;
}

.notes-title-pro {
  font-size: 1.6rem;
  font-weight: 700;
  color: #222;
  letter-spacing: 1px;
}

.notes-grid-pro {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
  gap: 32px;
  margin-top: 24px;
}

.note-card-pro {
  background: #fff;
  border-radius: 16px;
  box-shadow: 0 4px 18px rgba(64,158,255,0.08);
  padding: 28px 24px 18px 24px;
  transition: box-shadow 0.2s, transform 0.2s;
  cursor: pointer;
  position: relative;
  display: flex;
  flex-direction: column;
  min-height: 110px;
  border: 1.5px solid #f0f2f5;
  align-items: flex-start;
  text-align: left;
}

.note-card-pro:hover {
  box-shadow: 0 8px 32px rgba(64,158,255,0.16);
  transform: translateY(-4px) scale(1.02);
  border-color: #b3d8ff;
}

.note-card-header {
  display: grid;
  grid-template-columns: 1fr auto;
  align-items: center;
  width: 100%;
  margin-bottom: 10px;
}

.note-title-pro {
  font-size: 1.15rem;
  font-weight: 600;
  color: #222;
  margin: 0;
}

.note-date-pro {
  color: #bbb;
  font-size: 0.92rem;
  margin-left: auto;
  text-align: right;
  white-space: nowrap;
}

.note-preview-pro {
  font-size: 0.98rem;
  color: #666;
  margin-bottom: 18px;
  line-height: 1.6;
  flex: 1;
  overflow: hidden;
  display: -webkit-box;
  -webkit-line-clamp: 4;
  -webkit-box-orient: vertical;
}

.note-card-actions {
  display: flex;
  gap: 8px;
  justify-content: flex-end;
  width: 100%;
  text-align: right;
  opacity: 0;
  transition: opacity 0.2s;
}

.note-card-pro:hover .note-card-actions {
  opacity: 1;
}

.editor-header-pro {
  display: flex;
  align-items: center;
  gap: 18px;
  margin-bottom: 18px;
}

.back-btn-pro {
  margin-right: 8px;
}

.title-input-pro {
  flex: 1;
  font-size: 1.3rem;
  font-weight: 600;
  margin-right: 18px;
}

.editor-actions-pro {
  display: flex;
  gap: 12px;
}

.editor-content-pro {
  height: 420px;
  margin-bottom: 18px;
}

.auto-save-tip {
  color: #67c23a;
  font-size: 0.98rem;
  text-align: right;
  margin-top: 8px;
}

.preview-dialog {
  border-radius: 12px;
}

.preview-content {
  padding: 20px;
}

.preview-content h1 {
  font-size: 1.8rem;
  font-weight: 700;
  color: #222;
  margin-bottom: 24px;
}

.preview-content :deep(img) {
  max-width: 100%;
  height: auto;
}

@media (max-width: 768px) {
  .notes-card {
    padding: 20px;
  }
  
  .notes-grid-pro {
    grid-template-columns: 1fr;
  }
  
  .editor-content-pro {
    height: 300px;
  }
}

.notes-empty-pro {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #bbb;
  font-size: 1.1rem;
  padding: 60px 0 80px 0;
  min-height: 320px;
}
.notes-empty-svg {
  margin-bottom: 18px;
}
.notes-empty-text-pro {
  color: #999;
  font-size: 1.1rem;
}

/* 动画 */
.fade-card-enter-active, .fade-card-leave-active {
  transition: all 0.4s cubic-bezier(.25,.8,.25,1);
}
.fade-card-enter, .fade-card-leave-to {
  opacity: 0;
  transform: translateY(20px);
}

.right-align-btn {
  display: flex;
  justify-content: flex-end;
  align-items: center;
}

/* 美化Quill编辑器工具栏 */
::v-deep .ql-toolbar {
  justify-content: flex-start !important;
  text-align: left !important;
  border-radius: 10px 10px 0 0;
  box-shadow: 0 2px 8px rgba(64,158,255,0.08);
  background: #f8fafc;
  padding-left: 8px;
}
::v-deep .ql-toolbar .ql-formats {
  margin-right: 8px;
}
::v-deep .ql-toolbar button,
::v-deep .ql-toolbar .ql-picker {
  border-radius: 6px;
  transition: background 0.2s;
}
::v-deep .ql-toolbar button:hover,
::v-deep .ql-toolbar .ql-picker:hover {
  background: #e6f0fa;
}
::v-deep .ql-toolbar .ql-active {
  background: #d0eaff !important;
}
::v-deep .ql-container {
  border-radius: 0 0 10px 10px;
  background: #fff;
  min-height: 340px;
  font-size: 1.08rem;
}

.tags-layout {
  display: flex;
  flex-direction: row;
}
.tags-sidebar {
  width: 120px;
  background: #f8fafc;
  border-radius: 16px;
  margin-right: 32px;
  padding: 32px 0 0 0;
  display: flex;
  flex-direction: column;
  align-items: stretch;
  box-shadow: 0 2px 12px rgba(64,158,255,0.06);
  min-height: 600px;
}
.tag-item {
  padding: 12px 0 12px 32px;
  font-size: 1.08rem;
  color: #666;
  cursor: pointer;
  border-left: 4px solid transparent;
  transition: all 0.2s;
}
.tag-item.active {
  color: #409eff;
  font-weight: 700;
  background: #eaf6ff;
  border-left: 4px solid #409eff;
}
.note-tags {
  margin-bottom: 8px;
  display: flex;
  flex-wrap: wrap;
  gap: 6px 10px;
}

.add-tag-row {
  display: flex;
  align-items: center;
  padding: 0 0 12px 16px;
}

.tag-delete-btn {
  margin-left: 6px;
  color: #bbb;
  font-size: 12px;
  vertical-align: middle;
}
.tag-delete-btn:hover {
  color: #f56c6c;
}

/* 标签栏淡入淡出动画 */
.fade-tagbar-enter-active, .fade-tagbar-leave-active {
  transition: opacity 0.35s cubic-bezier(.25,.8,.25,1), transform 0.35s cubic-bezier(.25,.8,.25,1);
}
.fade-tagbar-enter, .fade-tagbar-leave-to {
  opacity: 0;
  transform: translateX(-30px);
}
</style> 